import 'dart:async';

import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:xcite/core/utils/ali.dart';

import '../../core/models/travel_log_model.dart';
import '../../core/providers/team_provider.dart';
import '../../core/providers/travel_log_provider.dart';
import '../../core/providers/user_provider.dart';
import '../../core/utils/popup_helper.dart';
import '../../core/utils/toast_helper.dart';

class SocialInteractionScreen extends ConsumerStatefulWidget {
  const SocialInteractionScreen({super.key});

  @override
  ConsumerState<SocialInteractionScreen> createState() =>
      _SocialInteractionScreenState();
}

class _SocialInteractionScreenState
    extends ConsumerState<SocialInteractionScreen> {
  final PageController _teamPageController = PageController();
  int _currentTeamIndex = 0;
  Timer? _autoScrollTimer;

  @override
  void initState() {
    super.initState();
    _startAutoScroll();
  }

  @override
  void dispose() {
    _autoScrollTimer?.cancel();
    _teamPageController.dispose();
    super.dispose();
  }

  void _startAutoScroll() {
    _autoScrollTimer = Timer.periodic(Duration(seconds: 3), (timer) {
      final teams = ref.read(teamProvider);
      if (teams.isNotEmpty && _teamPageController.hasClients) {
        final nextIndex = (_currentTeamIndex + 1) % teams.length;
        _teamPageController.animateToPage(
          nextIndex,
          duration: Duration(milliseconds: 500),
          curve: Curves.easeInOut,
        );
      }
    });
  }

  void _stopAutoScroll() {
    _autoScrollTimer?.cancel();
  }

  void _restartAutoScroll() {
    _stopAutoScroll();
    _startAutoScroll();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/resources/common_bg.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(child: _buildMainContent()),
      ),
    );
  }

  Widget _buildMainContent() {
    return SingleChildScrollView(
      child: [
        Container(
          padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 20.h),
          child: _buildPopularSection(),
        ),
        Container(
          padding: EdgeInsets.symmetric(horizontal: 16.w),
          child: Text('Spring outing team')
              .fontSize(24.sp)
              .fontWeight(FontWeight.bold)
              .textColor(Colors.white)
              .fontFamily('PoetsenOne'),
        ),
        SizedBox(height: 16.h),
        _buildTeamCarousel(),
        SizedBox(height: 24.h),
        Container(
          padding: EdgeInsets.symmetric(horizontal: 16.w),
          child: _buildTravelogueSection(),
        ),
        SizedBox(height: 20.h),
      ].toColumn(crossAxisAlignment: CrossAxisAlignment.start),
    );
  }

  Widget _buildPopularSection() {
    return [
      Text('Popular')
          .fontSize(24.sp)
          .fontWeight(FontWeight.bold)
          .textColor(Colors.black)
          .fontFamily('PoetsenOne'),
      SizedBox(height: 16.h),
      [
        Expanded(
          child: AspectRatio(
            aspectRatio: 193 / 209,
            child: Container(
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: AssetImage('assets/resources/topic_card.png'),
                  fit: BoxFit.fill,
                ),
              ),
            ).inkWell(
              onTap: () {
                GoRouter.of(context).push('/topic-list');
              },
            ),
          ),
        ),
        Expanded(
          child: AspectRatio(
            aspectRatio: 193 / 209,
            child: Container(
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: AssetImage('assets/resources/votes_card.png'),
                  fit: BoxFit.fill,
                ),
              ),
            ).inkWell(
              onTap: () {
                GoRouter.of(context).push('/vote');
              },
            ),
          ),
        ),
      ].toRow(),
    ].toColumn(crossAxisAlignment: CrossAxisAlignment.start);
  }

  Widget _buildTeamCarousel() {
    final teams = ref.watch(teamProvider);

    if (teams.isNotEmpty) {
      return AspectRatio(
        aspectRatio: 374 / 217,
        child: PageView.builder(
          controller: _teamPageController,
          onPageChanged: (index) {
            setState(() {
              _currentTeamIndex = index;
            });
            _restartAutoScroll();
          },
          itemCount: teams.length,
          itemBuilder: (context, index) {
            final team = teams[index];
            return _buildTeamCard(team);
          },
        ),
      );
    } else {
      return SizedBox(
        height: 200.h,
        child:
            Text(
              'No teams available',
            ).fontSize(16.sp).textColor(Colors.grey).center(),
      );
    }
  }

  Widget _buildTeamCard(dynamic team) {
    final currentUser = ref.watch(currentUserProvider);
    final isJoined = team.memberIds?.contains(currentUser?.id) ?? false;

    final userNotifier = ref.read(userProvider.notifier);
    final allUsers = userNotifier.getAllDefaultUsers();
    final creator = allUsers.firstWhere(
      (u) => u.id == team.creatorId,
      orElse: () => allUsers.first,
    );

    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/resources/team_card.png'),
            fit: BoxFit.fill,
          ),
        ),
        child: [
              Container(
                width: 128.w,
                height: 56.h,
                decoration: BoxDecoration(color: Colors.transparent),
              ).inkWell(
                onTap: () {
                  GoRouter.of(context).push('/create-team');
                },
              ),
              Spacer(),
              [
                SizedBox(width: 10.w),
                Container(
                  width: 128.w,
                  height: 128.w,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(8.r),
                    image: DecorationImage(
                      image: AssetImage(team.coverImage),
                      fit: BoxFit.cover,
                    ),
                  ),
                ),
                SizedBox(width: 12.w),
                Expanded(
                  child: [
                    Text(
                      team.teamName,
                      style: TextStyle(
                        fontSize: 18.sp,
                        fontFamily: 'PoetsenOne',
                        fontWeight: FontWeight.bold,
                        color: Colors.black,
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                    SizedBox(height: 8.h),
                    [
                      Container(
                        width: 20.w,
                        height: 20.w,
                        decoration: BoxDecoration(
                          shape: BoxShape.circle,
                          color: Color(0xFFFDF5E1),
                          border: Border.all(width: 1.w, color: Colors.black),
                        ),
                        child:
                            Icon(AliIcons.iconPeople2)
                                .iconSize(16.sp)
                                .iconColor(Color(0xFFFD66CD))
                                .center(),
                      ),
                      SizedBox(width: 8.w),
                      Text(
                        'Limit: ',
                      ).fontSize(12.sp).textColor(Colors.grey[600]),
                      Text('${team.maxMembers} people')
                          .fontSize(12.sp)
                          .fontFamily('PoetsenOne')
                          .fontWeight(FontWeight.bold)
                          .textColor(Colors.black),
                    ].toRow(),
                    SizedBox(height: 6.h),
                    [
                      Container(
                        width: 20.w,
                        height: 20.w,
                        decoration: BoxDecoration(
                          shape: BoxShape.circle,
                          color: Color(0xFFFDF5E1),
                          border: Border.all(width: 1.w, color: Colors.black),
                        ),
                        child:
                            Icon(AliIcons.iconTime)
                                .iconSize(14.sp)
                                .iconColor(Color(0xFFFD66CD))
                                .center(),
                      ),
                      SizedBox(width: 8.w),
                      Text(
                        'Entry deadline: ',
                      ).fontSize(12.sp).textColor(Colors.grey[600]),
                      Text(team.registrationDeadline.toString().split(' ')[0])
                          .fontSize(12.sp)
                          .fontFamily('PoetsenOne')
                          .fontWeight(FontWeight.bold)
                          .textColor(Colors.black),
                    ].toRow(),
                    SizedBox(height: 12.h),
                    [
                      [
                        Container(
                          width: 32.w,
                          height: 32.w,
                          decoration: BoxDecoration(
                            shape: BoxShape.circle,
                            image: DecorationImage(
                              image: AssetImage(creator.avatar),
                              fit: BoxFit.cover,
                            ),
                          ),
                        ),
                        SizedBox(width: 8.w),
                        Text(creator.username)
                            .fontSize(14.sp)
                            .textColor(Colors.black)
                            .fontFamily('PoetsenOne'),
                      ].toRow(),
                      Spacer(),
                      Container(
                        width: 90.w,
                        height: 36.h,
                        decoration: BoxDecoration(
                          image: DecorationImage(
                            image: AssetImage(
                              isJoined
                                  ? 'assets/resources/chat_button.png'
                                  : 'assets/resources/join_button.png',
                            ),
                            fit: BoxFit.fill,
                          ),
                        ),
                      ).inkWell(onTap: () => _handleTeamAction(team, isJoined)),
                    ].toRow(),
                  ].toColumn(crossAxisAlignment: CrossAxisAlignment.start),
                ),
              ].toRow(),
              Spacer(),
              _buildTeamIndicator(ref.watch(teamProvider).length),
            ]
            .toColumn(crossAxisAlignment: CrossAxisAlignment.start)
            .padding(right: 16.w, bottom: 10.h),
      ),
    );
  }

  /// 构建团队指示器
  Widget _buildTeamIndicator(int teamCount) {
    return [
      for (int i = 0; i < teamCount; i++)
        Container(
          width: i == _currentTeamIndex ? 12.w : 6.w,
          height: 6.w,
          margin: EdgeInsets.symmetric(horizontal: 2.w),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(3.r),
            color: i == _currentTeamIndex ? Color(0xFFFD66CD) : Colors.white,
          ),
        ),
    ].toRow(mainAxisAlignment: MainAxisAlignment.center);
  }

  /// 处理团队操作
  void _handleTeamAction(dynamic team, bool isJoined) {
    final currentUser = ref.read(currentUserProvider);

    if (currentUser == null) {
      // 显示登录提示
      PopupHelper.showLoginDialog(
        context,
        onLoginPressed: () {
          GoRouter.of(context).push('/login');
        },
        onCancelPressed: () {},
      );
      return;
    }

    if (isJoined) {
      // 已加入，跳转到聊天
      GoRouter.of(context).push(
        '/group-chat',
        extra: {'teamId': team.teamId, 'chatGroupId': team.chatGroupId},
      );
    } else {
      // 显示加入团队对话框
      PopupHelper.showJoinTeamDialog(
        context,
        onJoinPressed: () {
          // 执行加入团队逻辑
          _joinTeam(team);
        },
        onCancelPressed: () {
          // 取消加入
          ToastHelper.info('Join cancelled', context: context);
        },
      );
    }
  }

  /// 加入团队
  Future<void> _joinTeam(dynamic team) async {
    final currentUser = ref.read(currentUserProvider);
    if (currentUser == null) return;

    try {
      final teamNotifier = ref.read(teamProvider.notifier);
      final success = await teamNotifier.joinTeam(team.teamId, currentUser.id);

      if (mounted) {
        if (success) {
          ToastHelper.success('Joined team successfully!', context: context);

          setState(() {});
        } else {
          final teamData = teamNotifier.getTeamById(team.teamId);
          if (teamData != null) {
            if (teamData.isMember(currentUser.id)) {
              ToastHelper.error(
                'You are already a member of this team',
                context: context,
              );
            } else if (teamData.memberIds.length >= teamData.maxMembers) {
              ToastHelper.error('Team is full', context: context);
            } else if (DateTime.now().isAfter(teamData.registrationDeadline)) {
              ToastHelper.error(
                'Registration deadline has passed',
                context: context,
              );
            } else {
              ToastHelper.error('Failed to join team', context: context);
            }
          } else {
            ToastHelper.error('Team not found', context: context);
          }
        }
      }
    } catch (e) {
      if (mounted) {
        ToastHelper.error('Failed to join team', context: context);
      }
    }
  }

  /// 构建旅游日志部分
  Widget _buildTravelogueSection() {
    final travelLogs = ref.watch(travelLogProvider);

    return [
      // Travelogue Sharing标题
      Text('Travelogue Sharing')
          .fontSize(24.sp)
          .fontWeight(FontWeight.bold)
          .textColor(Colors.white)
          .fontFamily('PoetsenOne'),
      SizedBox(height: 16.h),
      // 两列布局
      [
        // 第一列
        Expanded(
          child:
              [
                for (int i = 0; i < travelLogs.length; i += 2)
                  if (i < travelLogs.length)
                    Padding(
                      padding: EdgeInsets.only(bottom: 12.h),
                      child: _buildTravelLogCard(travelLogs[i]),
                    ),
              ].toColumn(),
        ),
        SizedBox(width: 12.w),
        // 第二列（带发布按钮）
        Expanded(
          child:
              [
                // 发布按钮
                AspectRatio(
                  aspectRatio: 182 / 48,
                  child: Container(
                    width: double.infinity,
                    decoration: BoxDecoration(
                      image: DecorationImage(
                        image: AssetImage(
                          'assets/resources/release_button.png',
                        ),
                        fit: BoxFit.fill,
                      ),
                    ),
                  ).inkWell(
                    onTap: () {
                      GoRouter.of(context).push('/publish-travel-log');
                    },
                  ),
                ),
                SizedBox(height: 12.h),
                // 第二列的日志
                for (int i = 1; i < travelLogs.length; i += 2)
                  if (i < travelLogs.length)
                    Padding(
                      padding: EdgeInsets.only(bottom: 12.h),
                      child: _buildTravelLogCard(travelLogs[i]),
                    ),
              ].toColumn(),
        ),
      ].toRow(crossAxisAlignment: CrossAxisAlignment.start),
    ].toColumn(crossAxisAlignment: CrossAxisAlignment.start);
  }

  /// 构建旅游日志卡片
  Widget _buildTravelLogCard(TravelLogEntity travelLog) {
    final userNotifier = ref.read(userProvider.notifier);
    final allUsers = userNotifier.getAllDefaultUsers();

    final user =
        allUsers.isNotEmpty
            ? (allUsers.firstWhere(
              (u) => u.id == travelLog.userId,
              orElse: () => allUsers.first,
            ))
            : null;
    return AspectRatio(
      aspectRatio: 182 / 262,
      child: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/resources/log_bg.png'),
            fit: BoxFit.fill,
          ),
        ),
        child:
            [
              // 图片/视频区域
              Expanded(
                child: Hero(
                  tag: 'travel_log_image_${travelLog.logId}',
                  child: Container(
                    margin: EdgeInsets.all(8.w),
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(8.r),
                      image: DecorationImage(
                        image: AssetImage(
                          travelLog.isVideoType &&
                                  travelLog.videoCoverUrl != null
                              ? travelLog.videoCoverUrl!
                              : travelLog.mediaUrl,
                        ),
                        fit: BoxFit.cover,
                      ),
                    ),
                    child:
                        travelLog.isVideoType
                            ? Icon(AliIcons.iconPlayFill)
                                .iconSize(22.sp)
                                .iconColor(Colors.white.withValues(alpha: 0.8))
                                .center()
                            : null,
                  ),
                ),
              ),
              // 旅游日志详情文字
              Container(
                padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h),
                alignment: Alignment.centerLeft,
                child: Text(
                  travelLog.content,
                  style: TextStyle(
                    fontSize: 10.sp,
                    color: Colors.black87,
                    height: 1.2,
                  ),
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                  textAlign: TextAlign.start,
                ),
              ),
              // 底部信息
              Container(
                padding: EdgeInsets.all(8.w),
                child:
                    [
                      Container(
                        width: 28.w,
                        height: 28.w,
                        decoration: BoxDecoration(
                          shape: BoxShape.circle,
                          image: DecorationImage(
                            image: AssetImage(
                              user?.avatar ?? 'assets/resources/avatar1.png',
                            ),
                            fit: BoxFit.cover,
                          ),
                        ),
                      ),
                      SizedBox(width: 8.w),
                      Expanded(
                        child: Text(
                          user?.username ?? 'User',
                          style: TextStyle(
                            fontSize: 13.sp,
                            color: Colors.black,
                            fontFamily: 'PoetsenOne',
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ),
                      // 点赞按钮
                      _buildLikeButton(travelLog),

                      SizedBox(width: 8.w),
                    ].toRow(),
              ),
            ].toColumn(),
      ),
    ).inkWell(onTap: () => _handleTravelLogTap(travelLog));
  }

  /// 构建点赞按钮
  Widget _buildLikeButton(TravelLogEntity travelLog) {
    final currentUser = ref.watch(currentUserProvider);

    // 检查用户是否已点赞
    final isLiked =
        currentUser != null && travelLog.likedUserIds.contains(currentUser.id);

    // 确定图标颜色
    final iconColor =
        currentUser == null
            ? Colors.black
            : (isLiked ? Colors.red : Colors.black);

    return [
      Icon(AliIcons.iconGood).iconSize(22.sp).iconColor(iconColor),
      SizedBox(width: 4.w),
      Text('${travelLog.likeCount}').fontSize(13.sp).textColor(Colors.black),
    ].toRow().inkWell(onTap: () => _handleLike(travelLog));
  }

  /// 处理点赞操作
  void _handleLike(TravelLogEntity travelLog) {
    final currentUser = ref.read(currentUserProvider);

    if (currentUser == null) {
      // 显示登录提示弹窗
      PopupHelper.showLoginDialog(
        context,
        onLoginPressed: () {
          GoRouter.of(context).push('/login');
        },
        onCancelPressed: () {},
      );
      return;
    }

    // 执行点赞/取消点赞操作
    final travelLogNotifier = ref.read(travelLogProvider.notifier);

    travelLogNotifier.toggleLike(travelLog.logId, currentUser.id).then((
      success,
    ) {
      if (mounted) {
        if (success) {
          final isCurrentlyLiked = travelLog.likedUserIds.contains(
            currentUser.id,
          );
          if (isCurrentlyLiked) {
            ToastHelper.info('Unliked', context: context);
          } else {
            ToastHelper.success('Liked!', context: context);
          }
        } else {
          ToastHelper.error('Failed to update like status', context: context);
        }
      }
    });
  }

  /// 处理旅游日志点击
  void _handleTravelLogTap(TravelLogEntity travelLog) {
    GoRouter.of(context).push('/journey-detail/${travelLog.logId}');
  }
}
